#!/bin/bash

if [ "$(id -u)" != "0" ]; then
   echo "Script must be run as root !"
   exit 0
fi

if [ -z $TOP ]; then
	TOP=`cd .. && pwd`
fi
SCRIPT_DIR="$TOP/external/Legacy_patch/"

echo ""
date
echo -e "\033[36m==================================================="
echo "Creating Ubuntu/Debian SD Card (image) for OrangePI"
echo -e "===================================================\033[37m"
echo ""

_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
cd $_DIR
idir=linux-$distro             

# ===================================================
if [ "${2}" = "" ]; then
    echo "Source directory not specified."
    echo "USAGE: image_from_dir <img_name> [noformat] [2|pc|plus|one|lite|pcplus|plus2e]"
    exit 0
fi

if [ ! -d "$idir" ] || [ ! -d  "boot-$distro" ]; then
	sudo cp -rf $TOP/output/linux-$distro ./ 
	sudo cp -rf $TOP/output/boot-$distro ./
fi

if [ ! -d $idir ]; then
    echo "Source directory not found."
    echo "USAGE: image_from_dir <img_name> [noformat] [2|pc|plus|one|lite|pcplus|plus2e]"
    exit 0
fi
# ===================================================

. params.sh

# ********************************************************
# Linux partition size IS CALCULATED from directory size *
# ********************************************************
#_ext4size=`du -s $idir | awk '{print $idir}'`
_ext4size=650000
ext4sizeMB=$(expr $_ext4size / 1024)        
ext4size=$(expr $ext4sizeMB / 2 + $ext4sizeMB) 
linuxsize=$(expr $ext4sizeMB + 500)            
_boot_on_ext4="no"


image_name="OPI_$2"
odir="_extdir"
bootdir="_fatdir"

if [ "${3}" != "noformat" ] ; then
# =========
. format.sh
# =========
fi

# === Show info ===============
echo ""
echo "==== Info ===="
echo "    from: $idir"       
echo "      to: $sdcard"     
#echo "ext4boot: $_boot_on_ext4"
if [ "${_format}" = "btrfs" ] ; then
    echo "   btrfs: yes"
else
    echo "   btrfs: no"
fi
echo "dir size: $ext4sizeMB MB" 
echo "img size: $linuxsize MB"  
echo "=============="
echo ""

# -------------------------------------------------------------------
    
if [ ! "${_boot_on_ext4}" = "yes" ] ; then      
    if [ ! -d $bootdir ]; then
	mkdir -p $bootdir
    fi
    rm $bootdir/* > /dev/null 2>&1  
    sync
    umount $bootdir > /dev/null 2>&1
fi

if [ ! -d $odir ]; then                 
    mkdir -p $odir
fi
rm -rf $odir/* > /dev/null 2>&1
sync
umount $odir > /dev/null 2>&1
sleep 1

# ================
# MOUNT PARTITIONS
# ================

if [ "${_format}" = "btrfs" ] ; then             
    _mntopt="-o compress-force=lzo"
else
    _mntopt=""
fi

echo ""
echo "Mounting SD Card partitions..."

if [ ! "${_boot_on_ext4}" = "yes" ] ; then      
    if ! mount ${sdcard}1 $bootdir; then
	echo "ERROR mounting fat partitions..."
	exit 1
    fi
    if ! mount ${_mntopt} ${sdcard}2 $odir; then
	echo "ERROR mounting linux partitions..."
	umount $bootdir
	exit 1
    fi
    echo "FAT partitions mounted to $bootdir"
else
    if ! mount ${_mntopt} ${sdcard}1 $odir; then
	echo "ERROR mounting linux partitions..."
	exit 1
    fi
fi
echo "linux partition mounted to $odir"


#-----------------------------------------------------------------------------------------------
echo ""
echo "Copying file system to image ..."
echo ""

#-------------------------------------------------------------------------------
rsync -r -t -p -o -g -x --delete -l -H -D --numeric-ids -s --stats $idir/ $odir/
#-------------------------------------------------------------------------------
sync

# === Copy kernel, modules & scripts =============================================
if [ ! -d $odir/usr/local/bin ]; then
    mkdir -p $odir/usr/local/bin
fi
if [ ! -d $odir/boot ]; then
    mkdir -p $odir/boot
fi
if [ ! -d $odir/media/boot ]; then
    mkdir -p $odir/media/boot
fi
rm -r $odir/boot/* > /dev/null 2>&1
cp $SCRIPT_DIR/orange/uImage* $odir/boot > /dev/null 2>&1
cp $SCRIPT_DIR/orange/boot0_OPI.fex $odir/boot > /dev/null 2>&1
cp $SCRIPT_DIR/orange/u-boot_OPI*.fex $odir/boot > /dev/null 2>&1
cp fs_resize $odir/usr/local/bin > /dev/null 2>&1
cp install_* $odir/usr/local/bin > /dev/null 2>&1
if [ "${2}" = "noinstallscr" ] || [ "${3}" = "noinstallscr" ]; then
    rm $odir/usr/local/bin/install_*_desktop > /dev/null 2>&1
fi

if [ "${2}" = "zero" ]; then
    cp $TOP/output/uImage $odir/boot/uImage > /dev/null 2>&1
    cp $SCRIPT_DIR/script.bin $odir/boot > /dev/null 2>&1
fi


rm -r $odir/lib/modules/* > /dev/null 2>&1
cp -rf $TOP/output/lib/modules/3.4.39_zero/ $odir/lib/modules > /dev/null 2>&1
rm -r $odir/lib/firmware/* > /dev/null 2>&1
cp -rf $TOP/output/lib/firmware $odir/lib > /dev/null 2>&1
mkdir $odir/etc/firmware > /dev/null 2>&1
cp -rf $SCRIPT_DIR/boot_xr819.bin $odir/etc/firmware
cp -rf $SCRIPT_DIR/fw_xr819.bin $odir/etc/firmware
cp -rf $SCRIPT_DIR/sdd_xr819.bin $odir/etc/firmware
sudo chown -R root:root $odir/lib/* > /dev/null 2>&1

# ================================================================================
sync


# ************************
# Create fs_resize warning
# ************************
cat > ${odir}/usr/local/bin/fs_resize_warning << _EOF_
#!/bin/sh

echo -e "\033[31m\033[1m***********************************************"
echo -e "WARNING: TO RESIZE FILESYSTEM RUN:"
echo -e "sudo fs_resize or sudo /usr/local/bin/fs_resize"
echo -e "to remove this message run:"
echo -e "sudo rm /usr/local/bin/fs_resize_warning"
echo -e "***********************************************\033[22m\033[37m"
setterm -default

_EOF_
chmod +x ${odir}/usr/local/bin/fs_resize_warning

# ***************
# Create fstab
# ***************
echo "Creating \"fstab\""
echo "# OrangePI fstab" > $odir/etc/fstab
if [ "${_format}" = "btrfs" ] ; then
    echo "/dev/mmcblk0p2  /  btrfs subvolid=0,noatime,nodiratime,compress=lzo  0 1" >> $odir/etc/fstab
else
    echo "/dev/mmcblk0p2  /  ext4  errors=remount-ro,noatime,nodiratime  0 1" >> $odir/etc/fstab
fi
echo "/dev/mmcblk0p1  /media/boot  vfat  defaults  0 0" >> $odir/etc/fstab
echo "tmpfs /tmp  tmpfs nodev,nosuid,mode=1777  0 0" >> $odir/etc/fstab

echo ""

echo "sync, please wait ..."
sync

cp -rf -d $TOP/output/lib/modules/3.4.39_zero $odir/home/orangepi > /dev/null 2>&1
sudo chown root:root $odir/usr/bin/sudo && chmod 4755 $odir/usr/bin/sudo
# UMOUNT
if [ ! "${_boot_on_ext4}" = "yes" ] ; then
  if ! umount $bootdir; then
      echo "ERROR unmounting fat partition."
      exit 0
  fi
  rm -rf $bootdir/* > /dev/null 2>&1
  rmdir $bootdir > /dev/null 2>&1
fi  

if ! umount $odir; then
    echo "ERROR unmounting linux partitions."
    exit 0
fi

rm -rf $odir/* > /dev/null 2>&1
rmdir $odir > /dev/null 2>&1
sync


if [ -f ${sdcard}u ] && [ -f ${sdcard}2 ]; then
    echo "Creating SDCard image..."
    dd if=${sdcard}u of=${sdcard} > /dev/null 2>&1
    
    if [ -f ${sdcard}1 ]; then
	dd if=${sdcard}1 of=${sdcard} bs=1M conv=notrunc oflag=append > /dev/null 2>&1
    fi
    
    if [ -f ${sdcard}2 ]; then
	dd if=${sdcard}2 of=${sdcard} bs=1M conv=notrunc oflag=append > /dev/null 2>&1
    fi

    if [ "${_compress}" = "yes" ]; then 
	echo "Compressing image..."
	xz -z -k -9 -f -v $sdcard
	md5sum $sdcard > $sdcard.md5sum
	md5sum $sdcard.xz > $sdcard.xz.md5sum
    fi
fi

echo ""
date
echo ""
echo -e "\033[36m*********************"
echo "SDCard image created."
echo -e "*********************\033[37m"
echo ""

rm -rf $TOP/*.img
cp $sdcard $TOP/output/ -rf 
rm -rf $sdcard*
rm -rf linux-$distro boot-$distro

exit 0
